<?php
/**
 * +----------------------------------------------------------------------
 * | summer framework
 * +----------------------------------------------------------------------
 * | Copyright (c) 2020 https://github.com/suframe/think-admin All rights reserved.
 * +----------------------------------------------------------------------
 * | Author: summer <806115620@qq.com>  2020/3/30 14:30
 * +----------------------------------------------------------------------
 */
declare (strict_types=1);

namespace app\mall\model\traits;

use app\mall\model\MallRegion;
use think\Model;
use think\model\relation\BelongsTo;

/**
 * 获取地区
 * trait RegionTrait
 * @package app\mall\model\traits
 * @mixin Model
 * @property integer $region_id
 * @property MallRegion $region
 * @property array|object region_ids
 */
trait RegionTrait
{

    /**
     * 获取商品
     * @return BelongsTo
     */
    public function region(): BelongsTo
    {
        return $this->belongsTo(
            MallRegion::class,
            'region_id',
            'id')
            ->cache('modelBelongsCate' . $this->region_id, 60);
    }

    public function getRegionNameAttr()
    {
        return $this->region->value('name');
    }

    public function setRegionNamesAttr($value, $data)
    {
        if ($value) {
            $regionName = $value[count($value) - 1];
            if (!$regionName) {
                $this->set('region_id', 0);
            } else {
                $regionId = MallRegion::where('name', $regionName)->field(['id'])->value('id');
                $this->set('region_id', $regionId ?: 0);
            }
        }
        return $value ? json_encode($value, JSON_UNESCAPED_UNICODE) : '[]';
    }

    public function getRegionNamesAttr($value, $data)
    {
        return $value ? json_decode($value, true) : [];
    }
}